package net.oktaeder.office.view.filemailer;

import java.io.File;

import net.oktaeder.office.ConfigurationHelper;
import net.oktaeder.office.view.IMailer;
import net.oktaeder.office.view.Mail;
import net.oktaeder.office.view.MailDaemon;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Mailer that handles mails in a local folder
 * 
 * @author tuukka
 *
 */
public class FileMailer implements IMailer {

	private static Log log = LogFactory.getLog(FileMailer.class);
	private String inbox;
	private String outbox;
	private Configuration config;
	
	public FileMailer() throws Exception {
		try {
			log.trace("Creating an instance");
			config = ConfigurationHelper.getConfiguration();
			inbox = config.getString("file-mailer.inbox[@location]");
			outbox = config.getString("file-mailer.outbox[@location]");	
		} catch (Exception ex) {
			log.fatal("Failed to get instance of FileMailer", ex);
			throw new Exception("Failed to get instance of FileMailer", ex);
		}
	}

	/* (non-Javadoc)
	 * @see net.sourceforge.herculeum.office.view.IMailer#updateMailQueue()
	 */
	public void updateMailQueue() {
		try {
			File folder;
			File[] files;
			int count;
			MailDaemon daemon;
			Mail temp;
			
			daemon = MailDaemon.getInstance();
			folder = new File(outbox);						
			files = folder.listFiles();
			count = files.length;
			
			for(int i=0; i<count; i++) {
				temp = new Mail(files[i]);
				daemon.addMail(temp);
				files[i].delete();
			}
			
		} catch (Exception ex) {
			log.error("Mail retrieving failed, retrying in a moment");
		}
	}

	/* (non-Javadoc)
	 * @see net.sourceforge.herculeum.office.view.IMailer#getInbox()
	 */
	public String getInbox() {
		return inbox;
	}

	/* (non-Javadoc)
	 * @see net.sourceforge.herculeum.office.view.IMailer#setInbox(java.lang.String)
	 */
	public void setInbox(String inbox) {
		this.inbox = inbox;
	}

	/* (non-Javadoc)
	 * @see net.sourceforge.herculeum.office.view.IMailer#getOutbox()
	 */
	public String getOutbox() {
		return outbox;
	}

	/* (non-Javadoc)
	 * @see net.sourceforge.herculeum.office.view.IMailer#setOutbox(java.lang.String)
	 */
	public void setOutbox(String outbox) {
		this.outbox = outbox;
	}
}